<template>
  <el-dialog :close-on-click-modal="false" class="yy-modal--custom pc-temp-model" width="800px" v-model="isVisible" @close="onCancelModel" append-to-body>
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">排班导入</h4>
    </template>
    <div class="pc-temp-model_content">
      <div class="pc-temp-model_content-upload">
        <el-upload
            ref="uploadRef"
            class="pc-temp-model—-upload"
            :headers="upload.headers"
            multiple
            :limit="1"
            :action="getUploadUrl"
            drag
            accept=".xls,.xlsx"
            :auto-upload="false"
            :show-file-list="false"
            :on-progress="onProgress"
            :on-change="onFileUpload"
            :http-request="uploadSectionFile"
        >
          <el-icon class="el-icon--upload"><IconUploadFilled /></el-icon>
          <div class="el-upload__text">
            拖拽上传或 <em>点击上传</em>
          </div>
        </el-upload>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {UploadFilled as IconUploadFilled} from "@element-plus/icons-vue"
import {computed, defineEmits, defineExpose, reactive, ref} from "vue"
import {ElDialog, ElIcon, ElMessage, ElUpload, UploadFile, UploadFiles} from "element-plus"
import {ResourceModel} from "@/model/ResourceModel";
import StorageUtils from '@/utils/StorageUtils'
import {EnvConfig} from "@/utils";
import request from "@/utils/request";


const $emit = defineEmits({
  batchSaveFile: (temps: ResourceModel[]) => temps
})

const props = defineProps({

})
const upload = reactive({
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    'Authorization': "Bearer " + StorageUtils.getUserLoginToken()
  },
  responseType: 'blob',
  url: EnvConfig.baseApi + '/tr/screen/translate/template'
})

const getUploadUrl = computed(() => {
  return upload.url
})

const uploadRef = ref()
// 文件列表,显示在ui上
const files = ref([])
// 上传控件的文件列表，不显示在ui
let uploadFileArr = []


const isVisible = ref(false)
const isSaving = ref(false)

const onProgress = (event: Event,uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  uploadFileArr = uploadFiles
  // uploading
  const index = files.value.findIndex(item => item.uid === uploadFile.uid)
  if (index >= 0) {
    files.value.splice(index, 1, Object.assign(files.value[index], {status: uploadFile.status, percentage: uploadFile.percentage}))
  }
}

const onFileUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(uploadFile.status)
  isSaving.value = true
  uploadFileArr = uploadFiles
  if (uploadFile.status === 'ready') {
    uploadRef.value?.submit()
  } else {
    let status = uploadFile.status;
    // 如果没有获取到上传的文件地址，则标记为失败
    if (status === 'success') {
      ElMessage.success("文件转换成功")
      onCancelModel();
    }
  }
}

function uploadSectionFile(params){
  const data = new FormData();
  data.append(params.filename, params.file);
  request.post(params.action, data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    responseType: 'blob'
  })
      .then(resp => {
        console.log(resp);
        let b = new Blob([resp]);
        let url = window.URL.createObjectURL(b);  //生成文件流下载链接
        let a = document.createElement('a');      //创建一个a标签用来跳转
        a.href = url;                             // a标签 href  赋值 链接
        a.style.display = 'none'
        a.download = '排班导入模板.xlsx';                  //设置下载文件的文件名和文件格式
        document.body.appendChild(a);             //将标签DOM，放置页面
        a.click();
        window.URL.revokeObjectURL(url);     //释放 url 对象内存
        document.body.removeChild(a);//移除标签节点

        onCancelModel();
      }).catch(err => {
          console.log(err);
       });

}

const onShowModel = () => {
  isVisible.value = true
}

const onCancelModel = () => {
  isVisible.value = false
  files.value = []
  uploadFileArr = []
  uploadRef.value.clearFiles()
}

defineExpose({
  onShowModel
})

</script>

<style scoped lang="scss">
  .pc-temp-model {
    &_content {
      padding: 15px;
    }
  }

</style>
<style lang="scss">
.pc-temp-model—-upload {
  .el-upload-dragger {
    padding: 5px!important;
    .el-icon--upload {
      font-size: 45px;
      margin-bottom: 0px;
    }
  }
}
</style>
